﻿using System;
using System.Collections;
using System.Data;
using System.Reflection;

/// <summary>
/// 枚举值注释属性
/// </summary>
public class RemarkAttribute : Attribute
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="remark"></param>
    public RemarkAttribute(string remark)
    {
        Remark = remark;
    }

    /// <summary>
    /// 备注
    /// </summary>
    public string Remark { get; set; }

    private static readonly Hashtable Cache = Hashtable.Synchronized(new Hashtable());

    /// <summary>
    /// 得到枚举值的注释
    /// </summary>
    /// <param name="enumImpl"></param>
    /// <returns></returns>
    public static string GetEnumRemark(Enum enumImpl)
    {
        if (Cache.ContainsKey(enumImpl))
            return (string) Cache[enumImpl];
        var names = string.Empty;
        var type = enumImpl.GetType();
        var fieldNames = enumImpl.ToString().Split(',');
        for (int i = 0; i < fieldNames.Length; i++)
        {
            var fd = type.GetField(fieldNames[i].Trim());

            //#if DEBUG
            if (fd == null) return "";
            //#endif

            object[] attrs = fd.GetCustomAttributes(typeof (RemarkAttribute), false);
            string name = string.Empty;
            foreach (RemarkAttribute attr in attrs)
            {
                name = attr.Remark;
            }
            names += name;
            if (i < fieldNames.Length - 1)
            {
                names += ",";
            }
        }
        Cache.Add(enumImpl, names);
        return names;
    }

    /// <summary>
    /// 获取枚举类型的所有注释
    /// </summary>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static DataTable GetEnumAllRemark(Type enumValue)
    {
        FieldInfo fd;

        var table = new DataTable();
        table.Columns.AddRange(new[] {new DataColumn("ID", typeof (int)), new DataColumn("NAME", typeof (string))});

        if (enumValue.IsEnum)
        {
            var fields = enumValue.GetFields();
            foreach (var t in fields)
            {
                fd = t;
                var attrs = fd.GetCustomAttributes(typeof (RemarkAttribute), false);
                {
                    foreach (RemarkAttribute attr in attrs)
                    {
                        var name = attr.Remark;
                        var id = (int) fd.GetValue(Activator.CreateInstance(fd.FieldType));
                        table.Rows.Add(id, name);
                    }
                }
            }
        }

        table.AcceptChanges();
        return table;
    }
}